/*
 * Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.evenmo.string;

import java.util.ArrayList;
import java.util.List;

/**
 * This is Description voliate关键字
 * volatile只保证可见性，不保证原子性
 *
 * @author moyongjun
 * @date 2020/01/02
 */
public class ThreadDemo_voliate {

    /**volatile*/ int count=0;
    synchronized void m(){//注释掉synchronized放开volatile后就数据就会没有预期值了
        for (int i=0;i<10000;i++){
            count++;
        }
    }

    public static void main(String[] args) {
        ThreadDemo_voliate tv=new ThreadDemo_voliate();

        List<Thread> threads=new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(tv::m));
        }

        threads.forEach(thread -> thread.start());

        //让每个线程依次结束
        threads.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(tv.count);
    }
}
